import React, { useState } from "react"
import { Button, Form, Image, Input, Modal, Toast } from "antd-mobile"
import { useNavigate } from "react-router-dom"
import login from "@/assets/images/logo.png"
import icon_user from "../assets/images/icon_user.png"
import icon_pwd from "../assets/images/icon_pwd.png"
import * as request from "@/utils/request"

export default function Login() {
  const navigate = useNavigate()
  const [formData, setFormData] = useState({
    acc: "1",
    pwd: "1s",
  })
  // 登录方法
  const handleLogin = async () => {
    console.log(formData)

    if (!formData.acc || !formData.pwd) {
      Modal.alert({
        title: "提示",
        content: "用户名和密码不能为空，请重新输入",
        showCloseButton: true,
      })
      return false
    }
    const { code, token, id, msg } = await request.post("/movie/login", formData)
    localStorage.setItem("t_k", JSON.stringify(token))
    localStorage.setItem("id", JSON.stringify(id))
    Toast.show({
      content: msg,
      maskClickable: false,
      afterClose() {
        code === 0 ? navigate("/layout/movie") : ""
      },
    })
  }
  return (
    <div className='flex flex-col items-center'>
      {/* 图片 */}
      <Image
        className='my-20'
        src={login}
        width={80}
        height={80}
        fit='cover'
        style={{ borderRadius: 8 }}
      />
      <div>
        {/* 账号密码 */}
        <div>
          <Form layout='horizontal'>
            <Form.Item label={<img className='w-6' src={icon_user} />} name='username'>
              <Input
                value={formData.acc}
                placeholder='请输入用户名'
                clearable
                onChange={val => {
                  setFormData({ ...formData, acc: val })
                }}
              />
            </Form.Item>
            <Form.Item label={<img className='w-6' src={icon_pwd} />} name='password'>
              <Input
                value={formData.pwd}
                placeholder='请输入密码'
                clearable
                type='password'
                onChange={val => {
                  setFormData({ ...formData, pwd: val })
                }}
              />
            </Form.Item>
          </Form>
        </div>
        {/* 按钮 */}
        <div className='mt-5 mb-3 mx-3'>
          <Button className='w-full' block color='danger' size='large' onClick={handleLogin}>
            登录
          </Button>
        </div>
        {/* 超链接 */}
        <div className='flex justify-between mx-3'>
          <a className='text-red-500' href='/reg'>
            前往注册
          </a>
          <a className='text-red-500' href='/reg'>
            忘记密码
          </a>
        </div>
      </div>
    </div>
  )
}
